package com.example.videodemo;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.LinearInterpolator;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by dingfeng on 2016/7/12.
 */
public class VideoPlayActivity3 extends AppCompatActivity implements View.OnClickListener {

    private final static String TAG = "dingfeng";

    private RelativeLayout playLayout;
    private VideoView mVideoView;

    // control widget
    private View mControl;
    private FrameLayout top;
    private FrameLayout bottom;

    private ImageView btnBack;
    private TextView txtVideoTitle;
    private SeekBar mSeekBar;
    private TextView txtCurrent;
    private TextView txtDuration;
    private ImageView btnScreenMode;

    private ImageView prev;
    private ImageView play;
    private ImageView next;

    private ImageView loadImage;
    private ImageView lock;

    private ImageView mOperationBg;
    private ImageView mOperationPercent;
    private View mVolumeBrightnessLayout;

    private GestureDetector mGestureDetector;
    private AudioManager mAudioManager;
    private int mMaxVolume;
    private int mVolume = -1;
    private float mBrightness = -1f;

    private Configuration mConfiguration;

    private boolean IsScreenLock = false;
    private ProgressTask progressTask;
    private static int MAX = 100;

    private Uri mUri;
    private int currentPosition = 0;
    private int mDuration = 0;
    private boolean isPlaying = false;
    private boolean completed = false;
    private String mTitle = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play3);
        mConfiguration = getResources().getConfiguration();

        setupView();

        mGestureDetector = new GestureDetector(this, new MyGestureListener());
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mMaxVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);

        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        handleIntent(intent);
    }

    private void setupView() {
        playLayout = (RelativeLayout) findViewById(R.id.playLayout);
        mVideoView = (VideoView) findViewById(R.id.videoview);
        if (isLandScape()) {
            addLandScapeControlLayout();
        } else {
            addPortraitControlLayout();
        }

        getSupportFragmentManager().beginTransaction().add(R.id.container, new VideoListFragment()).commitAllowingStateLoss();
    }

    private void addPortraitControlLayout() {
        mControl = LayoutInflater.from(this).inflate(R.layout.play_control_portrait, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        playLayout.addView(mControl, lp);
        mControl.setOnTouchListener(controlTouch);

        top = (FrameLayout) mControl.findViewById(R.id.top);
        bottom = (FrameLayout) mControl.findViewById(R.id.bottom);

        btnBack = (ImageView) mControl.findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        txtVideoTitle = (TextView) mControl.findViewById(R.id.txtVideoTitle);

        mSeekBar = (SeekBar) mControl.findViewById(R.id.seekbar);
        mSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        txtCurrent = (TextView) mControl.findViewById(R.id.txtCurrent);
        txtDuration = (TextView) mControl.findViewById(R.id.txtDuration);

        btnScreenMode = (ImageView) mControl.findViewById(R.id.btnScreenMode);
        btnScreenMode.setImageResource(R.drawable.player_screen_adjust_enable);
        btnScreenMode.setOnClickListener(this);

        play = (ImageView) mControl.findViewById(R.id.play);
        play.setOnClickListener(this);

        loadImage = (ImageView) mControl.findViewById(R.id.loadImage);
    }

    private void addLandScapeControlLayout() {
        LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
        playLayout.setLayoutParams(lp1);

        mControl = LayoutInflater.from(this).inflate(R.layout.play_control_land, null);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        playLayout.addView(mControl, lp);
        mControl.setOnTouchListener(controlTouch);

        top = (FrameLayout) mControl.findViewById(R.id.top);
        bottom = (FrameLayout) mControl.findViewById(R.id.bottom);

        btnBack = (ImageView) mControl.findViewById(R.id.btnBack);
        btnBack.setOnClickListener(this);
        txtVideoTitle = (TextView) mControl.findViewById(R.id.txtVideoTitle);

        mSeekBar = (SeekBar) mControl.findViewById(R.id.seekbar);
        mSeekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        txtCurrent = (TextView) mControl.findViewById(R.id.txtCurrent);
        txtDuration = (TextView) mControl.findViewById(R.id.txtDuration);

        btnScreenMode = (ImageView) findViewById(R.id.btnScreenMode);
        btnScreenMode.setImageResource(R.drawable.player_screen_adjust_disable);
        btnScreenMode.setOnClickListener(this);

        prev = (ImageView) mControl.findViewById(R.id.prev);
        play = (ImageView) mControl.findViewById(R.id.play);
        next = (ImageView) mControl.findViewById(R.id.next);
        prev.setOnClickListener(this);
        play.setOnClickListener(this);
        next.setOnClickListener(this);

        loadImage = (ImageView) mControl.findViewById(R.id.loadImage);
        lock = (ImageView) mControl.findViewById(R.id.lock);
        lock.setOnClickListener(this);

        mVolumeBrightnessLayout = mControl.findViewById(R.id.operation_volume_brightness);
        mOperationBg = (ImageView) mControl.findViewById(R.id.operation_bg);
        mOperationPercent = (ImageView) mControl.findViewById(R.id.operation_percent);
    }

    private void handleIntent(Intent intent) {

        Log.d(TAG, "intent:" + intent.getAction());

        if (intent != null) {
            mVideoView.setVideoList(GetVideoAsyncTask.getVideoList());
            mUri = intent.getData();
            if (mUri != null) {
                play();
            } else {
                Toast.makeText(this, "视频URI不合法", Toast.LENGTH_SHORT).show();
            }
            mTitle = intent.getStringExtra("video_title");
            txtVideoTitle.setText(mTitle);
        }
    }

    private void play() {
        isPlaying = true;
        mVideoView.setVideoURI(mUri);
        mVideoView.setOnPreparedListener(onPreparedListener);
        mVideoView.setOnInfoListener(onInfoListener);
        mVideoView.setOnBufferingUpdateListener(onBufferingUpdateListener);
        mVideoView.setOnCompletionListener(onCompletionListener);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnBack:
                onBackPressed();
                break;
            case R.id.btnScreenMode:
                if (mConfiguration.orientation == Configuration.ORIENTATION_PORTRAIT) {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
                } else {
                    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                }
                break;
            case R.id.lock:
                if (IsScreenLock) {
                    unlockScreen();
                } else {
                    lockScreen();
                }
                break;
            case R.id.play:
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                    play.setImageResource(R.drawable.player_play_highlight);
                    isPlaying = false;
                } else {
                    mVideoView.start();
                    play.setImageResource(R.drawable.player_pause_highlight);
                    isPlaying = true;
                }
                break;
            case R.id.prev:
                if (!mVideoView.pre()) {
                    Toast.makeText(VideoPlayActivity3.this, "已是第一个视频！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.next:
                if (!mVideoView.next()) {
                    Toast.makeText(VideoPlayActivity3.this, "已是最后一个视频！", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private class MyGestureListener extends GestureDetector.SimpleOnGestureListener {

        @Override
        public boolean onSingleTapUp(MotionEvent e) {

            if (!IsScreenLock) {
                if (bottom.getVisibility() == View.VISIBLE) {
                    hideControl();
                } else {
                    showControl();
                }
            }
            if (isLandScape()) {
                if (lock.getVisibility() == View.VISIBLE) {
                    lock.setVisibility(View.GONE);
                } else {
                    lock.setVisibility(View.VISIBLE);
                }
            }
            return super.onSingleTapUp(e);
        }
    }

    float mLastY = 0;

    View.OnTouchListener controlTouch = new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (mGestureDetector.onTouchEvent(event)) {
                return true;
            }

            int height = mControl.getHeight();
            int width = mControl.getWidth();

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    mLastY = event.getY();
                    break;
                case MotionEvent.ACTION_MOVE:
                    if (!isLandScape() || IsScreenLock) break;

                    float x = event.getX();
                    float y = event.getY();
                    boolean up = y - mLastY < 0;
                    float distance = Math.abs(mLastY - y);

                    if (distance < 10) break; // 防止过于灵敏

                    float percent = distance * 2 / height;
                    if (percent > 1) percent = 1;
                    if (percent < 0) percent = 0;
                    if (x > width / 2) {
                        onVolumeSlide(percent, up);
                    } else {
                        onBrightnessSlide(percent, up);
                    }
                    break;
                case MotionEvent.ACTION_UP:
                    endGesture();
                    break;
                default:
                    break;
            }
            return true;
        }
    };

    /**
     * adjust volume
     *
     * @param percent
     * @param up      true--increase false--decrease
     */
    private void onVolumeSlide(float percent, boolean up) {
        int progressBarWidth = findViewById(R.id.operation_full).getLayoutParams().width;
        if (mVolume == -1) {
            mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
            if (mVolume < 0) {
                mVolume = 0;
            }
            mOperationBg.setImageResource(R.drawable.video_volumn_bg);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }
        // progress change
        int mWidth = progressBarWidth * mVolume / mMaxVolume;
        if (up) {
            mWidth = mWidth + (int) (progressBarWidth * percent);
        } else {
            mWidth = mWidth - (int) (progressBarWidth * percent);
        }
        if (mWidth > progressBarWidth) {
            mWidth = progressBarWidth;
        } else if (mWidth < 0) {
            mWidth = 0;
        }
        // volume change
        int index = mVolume;
        int increment = (int) (percent * mMaxVolume);
        if (up) {
            index = mVolume + increment;
        } else {
            index = mVolume - increment;
        }
        if (index > mMaxVolume) {
            index = mMaxVolume;
        } else if (index < 0) {
            index = 0;
        }
        // set volume
        mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);
        // set progress width
        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = mWidth;
        mOperationPercent.setLayoutParams(lp);
    }

    /**
     * adjust brightness
     *
     * @param percent
     * @param up      true--increase false--decrease
     */
    private void onBrightnessSlide(float percent, boolean up) {
        if (mBrightness < 0) {
            mBrightness = getWindow().getAttributes().screenBrightness;
            if (mBrightness <= 0.00f) {
                mBrightness = 0.50f;
            }
            if (mBrightness < 0.01f) {
                mBrightness = 0.01f;
            }
            mOperationBg.setImageResource(R.drawable.video_brightness_bg);
            mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
        }

        WindowManager.LayoutParams lpa = getWindow().getAttributes();
        if (up) {
            lpa.screenBrightness = mBrightness + percent;
        } else {
            lpa.screenBrightness = mBrightness - percent;
        }
        if (lpa.screenBrightness > 1.0f) {
            lpa.screenBrightness = 1.0f;
        } else if (lpa.screenBrightness < 0.01f) {
            lpa.screenBrightness = 0.01f;
        }
        // set brightness
        getWindow().setAttributes(lpa);
        // set progress width
        ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
        lp.width = (int) (findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness);
        mOperationPercent.setLayoutParams(lp);
    }

    private void endGesture() {
        mVolume = -1;
        mBrightness = -1f;
        // hide
        if (isLandScape()) {
            dismissHandler.removeMessages(HIDE_VOLUME_BRIGHTNESS);
            dismissHandler.sendEmptyMessageDelayed(HIDE_VOLUME_BRIGHTNESS, VOLUME_BRIGHTNESS_DELAYED);
        }
        dismissHandler.removeMessages(HIDE_CONTROL_LAYOUT);
        dismissHandler.sendEmptyMessageDelayed(HIDE_CONTROL_LAYOUT, CONTROL_LAYOUT_DELAYED);
    }

    private static final int HIDE_CONTROL_LAYOUT = 1;
    private static final int HIDE_VOLUME_BRIGHTNESS = 2;
    private static final int VOLUME_BRIGHTNESS_DELAYED = 500;
    private static final int CONTROL_LAYOUT_DELAYED = 5000;

    private Handler dismissHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HIDE_CONTROL_LAYOUT:
                    hideControl();
                    break;
                case HIDE_VOLUME_BRIGHTNESS:
                    mVolumeBrightnessLayout.setVisibility(View.GONE);
                    break;
            }
        }
    };

    private static final int PROGRESSBAR_UPDATE_DELAYED = 1000;

    // seek bar
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            updateSeekBar(mVideoView.getCurrentPosition());
            txtCurrent.setText(Utils.makeTimeString(mVideoView.getCurrentPosition()));
        }
    };

    private void updateSeekBar(long current) {
        if (mVideoView.isPlaying() && !isSeeking) {
            mSeekBar.setProgress((int) (current * 100 / mDuration));
        }
    }

    class ProgressTask implements Runnable {

        @Override
        public void run() {
            if (!completed) {
                mHandler.sendMessage(Message.obtain());
                mHandler.postDelayed(progressTask, PROGRESSBAR_UPDATE_DELAYED);
            }
        }
    }

    // control layout
    private void showControl() {
        top.setVisibility(View.VISIBLE);
        bottom.setVisibility(View.VISIBLE);
        // animation
        int topHeight = top.getHeight();
        int bottomHeight = bottom.getHeight();
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator topDriftY = ObjectAnimator.ofFloat(top, "translationY", -topHeight, 0.0f);
        ObjectAnimator bottomDriftY = ObjectAnimator.ofFloat(bottom, "translationY", bottomHeight, 0.0f);

        animatorSet.playTogether(topDriftY, bottomDriftY);
        animatorSet.setDuration(300);
        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.start();

        // hide after 3s
        dismissHandler.removeMessages(HIDE_CONTROL_LAYOUT);
        dismissHandler.sendEmptyMessageDelayed(HIDE_CONTROL_LAYOUT, 3000);
    }

    private void hideControl() {
        int topHeight = top.getHeight();
        int bottomHeight = bottom.getHeight();
        AnimatorSet animatorSet = new AnimatorSet();
        ObjectAnimator topDriftY = ObjectAnimator.ofFloat(top, "translationY", 0.0f, -topHeight);
        ObjectAnimator bottomDriftY = ObjectAnimator.ofFloat(bottom, "translationY", 0.0f, bottomHeight);

        animatorSet.playTogether(topDriftY, bottomDriftY);
        animatorSet.setDuration(300);
        animatorSet.setInterpolator(new DecelerateInterpolator());
        animatorSet.start();

        animatorSet.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                top.setVisibility(View.INVISIBLE);
                bottom.setVisibility(View.INVISIBLE);
            }
        });
    }

    // video loading animation
    ObjectAnimator animator;

    private void showLoadAnimation() {
        loadImage.setVisibility(View.VISIBLE);
        animator = ObjectAnimator.ofFloat(loadImage, "rotation", 0f, 360f);
        animator.setDuration(2000);
        animator.setRepeatCount(Animation.INFINITE);
        animator.setRepeatMode(Animation.RESTART);
        animator.setInterpolator(new LinearInterpolator());
        animator.start();
    }

    private void hideLoadAnimation() {
        loadImage.setVisibility(View.GONE);
        if (animator != null && animator.isRunning()) {
            animator.end();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mConfiguration = newConfig;
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            orientationChange(true);
        } else {
            orientationChange(false);
        }
    }

    // 横竖屏切换
    private void orientationChange(boolean isLandScape) {
        if (isLandScape) {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
            playLayout.setLayoutParams(lp);
            playLayout.removeView(mControl);
            addLandScapeControlLayout();
            if (lock != null) {
                lock.setVisibility(View.VISIBLE);
            }
        } else {
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT, (int) getResources().getDimension(R.dimen.video_height_portrait));
            playLayout.setLayoutParams(lp);
            playLayout.removeView(mControl);
            addPortraitControlLayout();
            if (lock != null) {
                lock.setVisibility(View.GONE);
            }
        }
        showControl();
        txtVideoTitle.setText(mTitle);
        if (completed) {
            txtCurrent.setText(Utils.makeTimeString(mDuration));
            mSeekBar.setProgress(mSeekBar.getMax());
        } else {
            txtCurrent.setText(Utils.makeTimeString(mVideoView.getCurrentPosition()));
            mSeekBar.setProgress(mSeekBar.getMax() * mVideoView.getCurrentPosition() / mDuration);
        }
        txtDuration.setText(Utils.makeTimeString(mDuration));
        setFullScreenDisplay(isLandScape);

        // after videoview's parent size changed, please set video layout
        playLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                playLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                Log.d(TAG, "playLayout.getWidth():" + playLayout.getWidth() + "    playLayout.getHeight():" + playLayout.getHeight());
                mVideoView.setVideoLayout(playLayout.getWidth(), playLayout.getHeight());
            }
        });
    }

    // 全屏模式切换
    private void setFullScreenDisplay(boolean enable) {
        if (enable) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    // 判断屏幕方向
    private boolean isLandScape() {
        mConfiguration = getResources().getConfiguration();
        int orientation = mConfiguration.orientation;
        if (orientation == Configuration.ORIENTATION_LANDSCAPE) {
            return true;
        }
        return false;
    }

    // 锁住屏幕，禁止返回操作
    private void lockScreen() {
        IsScreenLock = true;
        lock.setImageResource(R.drawable.player_control_lock);
        hideControl();
    }

    private void unlockScreen() {
        IsScreenLock = false;
        lock.setImageResource(R.drawable.player_control_unlock);
        showControl();
    }

    private boolean isSeeking = false;

    private SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            dismissHandler.removeMessages(HIDE_CONTROL_LAYOUT);
            isSeeking = true;
            isPlaying = false;
        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            isPlaying = true;
            isSeeking = false;
            dismissHandler.removeMessages(HIDE_CONTROL_LAYOUT);
            dismissHandler.sendEmptyMessageDelayed(HIDE_CONTROL_LAYOUT, CONTROL_LAYOUT_DELAYED);

            int progress = seekBar.getProgress();
            currentPosition = mVideoView.getDuration() * progress / 100;
            if (mVideoView != null) {
                mVideoView.seekTo(currentPosition);
//                showLoadAnimation();
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG, "onResume.....");
        if (isPlaying) {
            mVideoView.start();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG, "onPause.....");
        mVideoView.pause();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG, "onStop.....");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy.....");
        mVideoView.stop();
        completed = true;
        isPlaying = false;
        dismissHandler.removeMessages(HIDE_VOLUME_BRIGHTNESS);
        dismissHandler.removeMessages(HIDE_CONTROL_LAYOUT);
        mHandler.removeCallbacks(progressTask);
    }

    @Override
    public void onBackPressed() {
        if (IsScreenLock) {
            return;
        }
        if (mConfiguration.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        } else {
            super.onBackPressed();
        }
    }

    /**
     * Preserve the video's state when rotating the phone.
     */
    private static final String STATE_IS_PAUSED = "isPaused";
    private static final String STATE_PROGRESS_TIME = "progressTime";

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
        super.onSaveInstanceState(savedInstanceState);
        Log.d(TAG, "onSaveInstanceState:");
        savedInstanceState.putInt(STATE_PROGRESS_TIME, mVideoView.getCurrentPosition());
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        Log.d(TAG, "onRestoreInstanceState:");
        currentPosition = savedInstanceState.getInt(STATE_PROGRESS_TIME);
    }


    private MediaPlayer.OnPreparedListener onPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            completed = false;
            mDuration = mVideoView.getDuration();
            progressTask = new ProgressTask();
            new Thread(progressTask).start();
            txtDuration.setText(Utils.makeTimeString(mDuration));
        }
    };

    private MediaPlayer.OnInfoListener onInfoListener = new MediaPlayer.OnInfoListener() {
        @Override
        public boolean onInfo(MediaPlayer mp, int what, int extra) {
            if (what == MediaPlayer.MEDIA_INFO_BUFFERING_START) {
                mVideoView.pause();
                isPlaying = false;
            } else if (what == MediaPlayer.MEDIA_INFO_BUFFERING_END) {
                mVideoView.start();
                isPlaying = true;
            }
            return false;
        }
    };

    private MediaPlayer.OnBufferingUpdateListener onBufferingUpdateListener = new MediaPlayer.OnBufferingUpdateListener() {
        @Override
        public void onBufferingUpdate(MediaPlayer mp, int percent) {
//            Log.d(TAG, "onBufferingUpdate:" + percent);
//            mSeekBar.setSecondaryProgress(percent);
        }
    };


    private MediaPlayer.OnCompletionListener onCompletionListener = new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mp) {
            Log.d(TAG, "onCompletion...");
            complete();
        }
    };

    private void complete() {
        completed = true;
        mHandler.removeCallbacks(progressTask);
        txtCurrent.setText(Utils.makeTimeString(mDuration));
        mSeekBar.setProgress(MAX);
    }


}
